package com.ruoyix.flowable.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyix.common.core.domain.entity.SysMenu;
import com.ruoyix.common.utils.StringUtils;
import com.ruoyix.common.core.page.TableDataInfo;
import com.ruoyix.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyix.flowable.domain.vo.BpmFormVo;
import com.ruoyix.flowable.domain.vo.BpmTaskVo;
import com.ruoyix.flowable.mapper.BpmFormMapper;
import lombok.RequiredArgsConstructor;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.FlowElement;
import org.flowable.bpmn.model.UserTask;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.stereotype.Service;
import com.ruoyix.flowable.domain.bo.BpmTaskAssigneeBo;
import com.ruoyix.flowable.domain.vo.BpmTaskAssigneeVo;
import com.ruoyix.flowable.domain.BpmTaskAssignee;
import com.ruoyix.flowable.mapper.BpmTaskAssigneeMapper;
import com.ruoyix.flowable.service.IBpmTaskAssigneeService;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Collection;

/**
 * 流程定义设置Service业务层处理
 *
 * @author ruoyi
 * @date 2023-11-22
 */
@RequiredArgsConstructor
@Service
public class BpmTaskAssigneeServiceImpl implements IBpmTaskAssigneeService {

    private final BpmTaskAssigneeMapper baseMapper;

    private final BpmFormMapper bpmFormMapper;

    private final RepositoryService repositoryService;

    /**
     * 查询流程定义设置
     */
    @Override
    public BpmTaskAssigneeVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }


    /**
     * 查询节点信息
     * @param nodeId 节点ID
     * @param nodeName 节点名称
     * @param processDefinitionId
     * @return
     */
    @Override
    public BpmTaskAssigneeVo queryByNodeIdAndNodeKey(String nodeId, String nodeName, String processDefinitionId) {
        QueryWrapper<BpmTaskAssignee> wrapper = new QueryWrapper<>();
        wrapper.eq("node_id", nodeId).eq("node_name", nodeName).eq("process_definition_id",processDefinitionId);
        BpmTaskAssigneeVo bpmTaskAssigneeVo = baseMapper.selectVoOne(wrapper);

        return ObjectUtil.isEmpty(bpmTaskAssigneeVo)?new BpmTaskAssigneeVo():bpmTaskAssigneeVo;
    }

    /**
     * 查询流程定义设置列表
     */
    @Override
    public TableDataInfo<BpmTaskAssigneeVo> queryPageList(String processDefinitionId) {

        List<BpmTaskAssigneeVo> result = new ArrayList<>();
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(processDefinitionId).singleResult();

        // 获取 BpmnModel
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinitionId);

        // 获取流程定义中的所有流程元素
        Collection<FlowElement> flowElements = bpmnModel.getProcesses().get(0).getFlowElements();

        // 遍历流程元素，筛选出所有的用户任务节点
        for (FlowElement element : flowElements) {
            if (element instanceof UserTask) {
//                UserTask userTask = (UserTask) element;
                BpmTaskAssigneeVo bpmTaskAssigneeVo = new BpmTaskAssigneeVo();
                bpmTaskAssigneeVo.setProcessDefinitionId(processDefinitionId);
                bpmTaskAssigneeVo.setNodeId(element.getId());
                bpmTaskAssigneeVo.setNodeName(element.getName());
                bpmTaskAssigneeVo.setProcessDefinitionKey(processDefinition.getKey());
                result.add(bpmTaskAssigneeVo);
            }
        }
        return TableDataInfo.build(result);
    }

    /**
     * 查询流程定义设置列表
     */
    @Override
    public List<BpmTaskAssigneeVo> queryList(BpmTaskAssigneeBo bo) {
        LambdaQueryWrapper<BpmTaskAssignee> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<BpmTaskAssignee> buildQueryWrapper(BpmTaskAssigneeBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<BpmTaskAssignee> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getProcessDefinitionId()), BpmTaskAssignee::getProcessDefinitionId, bo.getProcessDefinitionId());
        lqw.eq(StringUtils.isNotBlank(bo.getChooseWay()), BpmTaskAssignee::getChooseWay, bo.getChooseWay());
        lqw.eq(StringUtils.isNotBlank(bo.getNodeId()), BpmTaskAssignee::getNodeId, bo.getNodeId());
        lqw.like(StringUtils.isNotBlank(bo.getNodeName()), BpmTaskAssignee::getNodeName, bo.getNodeName());
        lqw.eq(StringUtils.isNotBlank(bo.getProcessDefinitionKey()), BpmTaskAssignee::getProcessDefinitionKey, bo.getProcessDefinitionKey());
        lqw.eq(StringUtils.isNotBlank(bo.getAssignee()), BpmTaskAssignee::getAssignee, bo.getAssignee());
        lqw.eq(StringUtils.isNotBlank(bo.getAssigneeId()), BpmTaskAssignee::getAssigneeId, bo.getAssigneeId());
        lqw.eq(bo.getBusinessRuleId() != null, BpmTaskAssignee::getBusinessRuleId, bo.getBusinessRuleId());
        lqw.eq(bo.getDialogAssignee() != null, BpmTaskAssignee::getDialogAssignee, bo.getDialogAssignee());
        lqw.eq(bo.getMultiple() != null, BpmTaskAssignee::getMultiple, bo.getMultiple());
        lqw.eq(StringUtils.isNotBlank(bo.getMultipleColumn()), BpmTaskAssignee::getMultipleColumn, bo.getMultipleColumn());
        lqw.eq(bo.getCanBack() != null, BpmTaskAssignee::getCanBack, bo.getCanBack());
        lqw.eq(bo.getCanDelegate() != null, BpmTaskAssignee::getCanDelegate, bo.getCanDelegate());
        lqw.eq(bo.getCanCopy() != null, BpmTaskAssignee::getCanCopy, bo.getCanCopy());
        lqw.eq(bo.getCanAddSignature() != null, BpmTaskAssignee::getCanAddSignature, bo.getCanAddSignature());
        lqw.eq(bo.getCanReduceSignature() != null, BpmTaskAssignee::getCanReduceSignature, bo.getCanReduceSignature());
        lqw.eq(StringUtils.isNotBlank(bo.getTaskListener()), BpmTaskAssignee::getTaskListener, bo.getTaskListener());
        lqw.eq(bo.getAutoApproval() != null, BpmTaskAssignee::getAutoApproval, bo.getAutoApproval());
        lqw.eq(bo.getFormId() != null, BpmTaskAssignee::getFormId, bo.getFormId());
        lqw.eq(bo.getFormType() != null, BpmTaskAssignee::getFormType, bo.getFormType());
        lqw.eq(StringUtils.isNotBlank(bo.getFormOption()), BpmTaskAssignee::getFormOption, bo.getFormOption());
        lqw.eq(StringUtils.isNotBlank(bo.getFormFields()), BpmTaskAssignee::getFormFields, bo.getFormFields());
        lqw.eq(StringUtils.isNotBlank(bo.getFormCustomCreatePath()), BpmTaskAssignee::getFormCustomCreatePath, bo.getFormCustomCreatePath());
        lqw.eq(StringUtils.isNotBlank(bo.getFormCustomViewPath()), BpmTaskAssignee::getFormCustomViewPath, bo.getFormCustomViewPath());
        return lqw;
    }

    /**
     * 新增流程定义设置
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(BpmTaskAssigneeBo bo) {
        BpmTaskAssignee add = BeanUtil.toBean(bo, BpmTaskAssignee.class);
        validEntityBeforeSave(add);
        BpmFormVo bpmFormVo = bpmFormMapper.selectVoById(bo.getFormId());
        if( bo.getFormType() == 0 && ObjectUtil.isNotEmpty(bpmFormVo)){
            add.setFormFields(bpmFormVo.getFormFields());
            add.setFormOption(bpmFormVo.getFormOption());
        }else if (bo.getFormType() == 0 && ObjectUtil.isEmpty(bpmFormVo)){
            throw new RuntimeException("流程表单未配置");
        }

        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改流程定义设置
     */
    @Override
    public Boolean updateByBo(BpmTaskAssigneeBo bo) {
        BpmTaskAssignee update = BeanUtil.toBean(bo, BpmTaskAssignee.class);
        validEntityBeforeSave(update);
        BpmFormVo bpmFormVo = bpmFormMapper.selectVoById(bo.getFormId());
        if( bo.getFormType() == 0 && ObjectUtil.isNotEmpty(bpmFormVo)){
            update.setFormFields(bpmFormVo.getFormFields());
            update.setFormOption(bpmFormVo.getFormOption());
        }
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(BpmTaskAssignee entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除流程定义设置
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }


    @Override
    public BpmTaskAssigneeVo selectByDefineIdAndTaskKey(String processDefinitionId ,String nodeId) {
        QueryWrapper<BpmTaskAssignee> wrapper = Wrappers.query();
        wrapper.eq("process_definition_id",processDefinitionId).eq("node_id",nodeId);
        return baseMapper.selectVoOne(wrapper);

    }
}

